package com.zhuangjie.rider.helper;

import com.zhuangjie.redis.helper.RedisEnhanceOperationHelper;
import com.zhuangjie.rider.constant.DeliveryOrderConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 调度间隔保护
 *
 * @author zhuangjie
 * @date 2024/01/27
 */
@Component
public class DispatchIntervalProtection {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisEnhanceOperationHelper redisEnhanceOperationHelper;

    private static final String KEY_PREFIX = "rider::protection::";
    private static final String VALUE = "__UnderProtection__";

    /**
     * 构造保护
     *
     * @param riderId 骑手id
     */
    public void constructProtection(Long riderId) {
        redisTemplate.opsForValue().set(KEY_PREFIX+riderId,VALUE, DeliveryOrderConstant.ORDER_SCHEDULING_INTERVAL, TimeUnit.SECONDS);
    }
    /**
     * 并进行构造保护
     */
    public Boolean tryConstructProtection(Long riderId) {
        String key = KEY_PREFIX + riderId;
        return redisEnhanceOperationHelper.trySetStringKV(key,VALUE,DeliveryOrderConstant.ORDER_SCHEDULING_INTERVAL, TimeUnit.SECONDS);
    }


    /**
     *  移除保护
     */
    public void removeProtection(Long riderId) {
        redisTemplate.delete(KEY_PREFIX+riderId);
    }
    /**
     * 过滤掉保护的
     */
    public List<Long> filterProtection(List<Long> riderIds) {
        List<String> multiGetKeys = riderIds.stream().map(riderId -> KEY_PREFIX + riderId).collect(Collectors.toList());
        List<Object> values = redisTemplate.opsForValue().multiGet(multiGetKeys);
        // 无保护的骑手id
        List<Long> unprotectedRiderIds = new ArrayList<>();
        for (int i = 0; i < values.size(); i++) {
            if (values.get(i) == null) {
                unprotectedRiderIds.add(riderIds.get(i));
            }
        }
        return unprotectedRiderIds;
    }
}
